package com.cosmoplat.gfqd.processor;

import com.cosmoplat.gfqd.config.BootStrapConfig;
import com.cosmoplat.gfqd.constants.Constants;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 用于基于骨架项目生成新项目后批量修改yml文件
 */
public class BatchUpdatePomXmlFile {

    private static String ARCHETYPE_PACKAGE;

    public static void update(BootStrapConfig config) {

        if (config != null) {
            System.out.println("Loaded bootstrap: " + config);
            // Access config values
            ARCHETYPE_PACKAGE = config.getCreateProject().getArchetypePackage();
        }

        // 获取当前目录的路径
        Path startPath = Paths.get(Constants.PROJECTS_ARCHETYPE_RESOURCES);

        try {
            // 遍历所有 pom.xml 文件
            List<Path> pomFiles = findPomFiles(startPath);

            // 修改所有找到的 pom.xml 文件
            for (Path pomFilePath : pomFiles) {
                System.out.println("Processing file: " + pomFilePath);
                updatePomFile(pomFilePath);
            }
        } catch (IOException e) {
            System.err.println("An error occurred while processing POM files: " + e.getMessage());
        }
    }

    // 遍历目录并找到所有 pom.xml 文件
    private static List<Path> findPomFiles(Path startPath) throws IOException {
        try (Stream<Path> stream = Files.walk(startPath)) {
            return stream
                    .filter(file -> !Files.isDirectory(file))
                    .filter(file -> file.getFileName().toString().equals(Constants.POM_XML_FILE))
                    .collect(Collectors.toList());
        }
    }

    private static void updatePomFile(Path pomFilePath) {
        try {
            List<String> lines = Files.readAllLines(pomFilePath);
            List<String> modifiedLines = new ArrayList<>();

            for (String line : lines) {
                // 检查 <mainClass> 标签
                if (line.contains("<mainClass>") && line.contains(ARCHETYPE_PACKAGE)) {
                    // 替换为 ${groupId}
                    line = line.replace(ARCHETYPE_PACKAGE, "${groupId}");
                }

                // 添加处理后的行
                modifiedLines.add(line);
            }
            // 将修改后的内容写回文件
            Files.write(pomFilePath, modifiedLines);
            System.out.println("Updated file: " + pomFilePath);
        } catch (IOException e) {
            System.err.println("An error occurred while updating the file: " + pomFilePath + " - " + e.getMessage());
        }
    }
}
